package com.bubbo.rpc.client.util;

import com.bubbo.rpc.client.util.serialize.Serializer;
import com.bubbo.rpc.client.util.serialize.impl.ProtostuffSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by waasdasd on 2017/3/31.
 */
public class Encoder extends MessageToByteEncoder {

    private Class<?> genericClass;

    private Serializer serializer;

    public Encoder(Class<?> genericClass) {
        this.genericClass = genericClass;
        this.serializer = new ProtostuffSerializer();
    }

    public Encoder(Class<?> genericClass,Serializer serializer) {
        this.genericClass = genericClass;
        if(serializer==null){
            this.serializer = new ProtostuffSerializer();
        }
        this.serializer = serializer;
    }

    @Override
    public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
        if (genericClass.isInstance(in)) {
            byte[] data = serializer.serialize(in);
            out.writeInt(data.length);
            out.writeBytes(data);
        }
    }
}
